package com.uaroadshow.api.handler.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.JsonUtils;
import com.uaroadshow.api.handler.PaymentHandler;
import com.uaroadshow.api.rao.PaymentRao;

/**
 * 
 * @author mohanlan
 *
 */
@Component("paymentHandler")
public class PaymentHandlerImpl implements PaymentHandler {
    
	private static final Logger logger = LoggerFactory.getLogger(PaymentHandler.class);
	
    @Value("#{ctx['payment.host']}")
    private String paymentHost;
    
    @Rao
    private PaymentRao paymentRao;
    
    /*
     * (non-Javadoc)
     * @see com.demo2do.mobile.web.controller.handler.PaymentHandler#generateWechatPayContext(java.util.Map)
     */
    public Map<String, Object> generateWechatPayContext(Map<String, Object> params) {
        
    	String requestBody = JsonUtils.toJson(params);
    	
    	logger.trace("#generateWechatPayContext - start call payemnt with requestBody[{}]", requestBody);
        
        HttpResult httpResult = paymentRao.getPrepareData(paymentHost + "/prepare", requestBody);
        
        logger.trace("#generateWechatPayContext - get httpResult [{}]", JsonUtils.toJson(httpResult));
        
        if(!httpResult.isValid()) {
            throw new BusinessException("生成支付请求失败");
        }
        
        HttpResult responseResult = JsonUtils.parse(httpResult.getResponseText(), HttpResult.class);
        
        if(!responseResult.isValid()) {
        throw new BusinessException(responseResult.getMessage());
        }
        
        return responseResult.getData();
    }
    
}
